package com.huanzhidadi.feignservice.interceptor;

import com.huanzhidadi.feignservice.config.UserContextHolder;
import com.huanzhidadi.feignservice.model.LoginUser;
import com.huanzhidadi.feignservice.util.RedisUtil;
import com.huanzhidadi.feignservice.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
@Component
public class UserContextInterceptor implements HandlerInterceptor {

	@Autowired
	private TokenUtil tokenUtil;

	@Autowired
	private RedisUtil redisUtil;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse respone, Object arg2) throws Exception {
		log.info("common UserContextInterceptor request.getRequestURI():" + request.getRequestURI());
		log.debug("common UserContextInterceptor request.getQueryString():" + request.getQueryString());

		String token = request.getHeader("token");

		log.info("token: " + token);
		String userId = tokenUtil.getIdFromToken(token);
		// 从redis中获取用户信息
		LoginUser loginUser = redisUtil.getObject("security:" + userId, LoginUser.class);
		if (!Objects.isNull(loginUser)) {
			UserContextHolder.set(loginUser);
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse respone, Object arg2, ModelAndView arg3)
			throws Exception {
		// DOING NOTHING
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse respone, Object arg2, Exception arg3)
			throws Exception {
		UserContextHolder.shutdown();
	}

}
